using System;
using System.Linq;
using System.Text;
using System.Transactions;
using System.Collections.Generic;
using System.Web;
using Commons.Entity.CommonEnums;
using EF.Commons.Background.Entity;
namespace Common.Background.Data
{

    /// <summary>
    /// 职员信息       
    /// </summary>
    public class WebManageUsersRepository : BackgroundRepositoryBase, IWebManageUsersRepository
    {
        IWebManageUser_StrategyRepository iWebManageUser_StrategyRepository = null;
        IWebDepartmentsRepository iWebDepartmentsRepository = null;

        public WebManageUsersRepository()
        {
            iWebManageUser_StrategyRepository = new WebManageUser_StrategyRepository();
            iWebDepartmentsRepository = new WebDepartmentsRepository();
        }
        #region IWebManageUsersRepository 成员

        /// <summary>
        /// 添加职员
        /// </summary>
        /// <param name="WebManageUsers"></param>
        public void AddWebManageUsers(WebManageUsers WebManageUsers)
        {
            using (TransactionScope tran = new TransactionScope())
            {
                try
                {
                    var iWebManageUsersRpstry = new WebManageUsersRepository();
                    var iWebManageUser_WebManageRolesRepository = new WebManageUser_WebManageRolesRepository();
                    WebManageUsers objWMU = new WebManageUsers();
                    using (var ts2 = new TransactionScope())
                    {
                        try
                        {
                            #region
                            objWMU.LoginName = WebManageUsers.LoginName;
                            objWMU.Email = WebManageUsers.Email;
                            objWMU.RealName = WebManageUsers.RealName;
                            objWMU.Gender = WebManageUsers.Gender;
                            objWMU.Mobile = WebManageUsers.Mobile;
                            objWMU.Phone = WebManageUsers.Phone;
                            objWMU.Birthday = WebManageUsers.Birthday;
                            objWMU.Description = WebManageUsers.Description;
                            objWMU.AvatarUrl = WebManageUsers.AvatarUrl;
                            objWMU.QQ = WebManageUsers.QQ;
                            objWMU.MSN = WebManageUsers.MSN;
                            objWMU.Rtx = WebManageUsers.Rtx;
                            objWMU.DepartmentID = WebManageUsers.DepartmentID;
                            objWMU.CreateDate = DateTime.Now;
                            objWMU.UpdateDate = DateTime.Now;
                            objWMU.Status = (int)Status.Normal;
                            objWMU.Operator = WebManageUsers.Operator;
                            this.Insert(objWMU);
                            #endregion
                            ts2.Complete();
                        }
                        catch (Exception err)
                        {
                            throw err;
                        }
                        finally
                        {
                            ts2.Dispose();
                        }
                        int ManageUserID = (from _objMUID in
                                                this.GetEntities<WebManageUsers>().Where(item =>
                                                item.Status == (int)Status.Normal)
                                            select _objMUID.ManageUserID).Max();
                        List<WebManageUser_WebManageRoles> list = new List<WebManageUser_WebManageRoles>();
                        foreach (var item in WebManageUsers.WebManageUser_WebManageRoles_Extend)
                        {
                            list.Add(new WebManageUser_WebManageRoles()
                            {
                                ManageUserID = ManageUserID,
                                ManageRoleID = item.ManageRoleID,
                            });
                        }
                        iWebManageUser_WebManageRolesRepository.Insert(list);
                        tran.Complete();
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    tran.Dispose();
                }
            }
        }
        public IQueryable<WebManageUsers_Ext> GetDetailModel()
        {
            IWebManageUser_WebManageRolesRepository iWebManageUser_WebManageRolesRepository = new WebManageUser_WebManageRolesRepository();

            var linq = from data in this.GetEntities<WebManageUsers>()
                       join data2 in iWebDepartmentsRepository.GetEntities<WebDepartments>()
                       on data.DepartmentID equals data2.DepartmentID
                       join data3 in new WebManageUser_WebManageRolesRepository().GetDetailModel()
                       on data.ManageUserID equals data3.ManageUserID into list
                       select new WebManageUsers_Ext
                       {
                           ManageUserID = data.ManageUserID,
                           LoginName = data.LoginName,
                           Password = data.Password,
                           RealName = data.RealName,
                           Gender = data.Gender,
                           Phone = data.Phone,
                           Mobile = data.Mobile,
                           Email = data.Email,
                           QQ = data.QQ,
                           MSN = data.MSN,
                           Rtx = data.Rtx,
                           Birthday = data.Birthday,
                           Description = data.Description,
                           DepartmentID = data.DepartmentID,
                           CreateDate = data.CreateDate,
                           UpdateDate = data.UpdateDate,
                           Operator = data.Operator,
                           Status = data.Status,
                           WebDepartments_Extend = data2,
                           WebManageUser_WebManageRoles_Extend = list,
                           AvatarUrl = data.AvatarUrl,
                       };
            return linq;
        }
        public WebManageUsers UserLogin(WebManageUsers webManageUsers)
        {
            bool flag = true;
            WebManageUsers linq = this.GetEntities<WebManageUsers>().Where(i =>
                i.LoginName == webManageUsers.LoginName
               && i.Password == webManageUsers.Password
               && i.Status == (int)Status.Normal).FirstOrDefault();
            if (linq != null)
            {
                var mgr = iWebManageUser_StrategyRepository.GetModel().Where(i => i.Status == (int)Status.Normal && i.ManageUserID == linq.ManageUserID);

                linq.WebDepartments_Extend = iWebDepartmentsRepository.GetEntity<WebDepartments>(linq.DepartmentID) ?? new WebDepartments { DepartmentName = "" };
                if (mgr != null && mgr.Count() > 0)
                    foreach (var i in mgr.ToList())
                    {
                        if (!string.IsNullOrEmpty(i.IPArea))
                        {
                            List<string> standardIP = i.IPArea.Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                            List<string> currentIP = GetRealIp().Split(new char[] { '.' }, StringSplitOptions.RemoveEmptyEntries).ToList();
                            if (standardIP[0] != "*")
                                if (standardIP[0] == currentIP[0]) flag = flag && true; else flag = flag && false;
                            if (standardIP[1] != "*")
                                if (standardIP[1] == currentIP[1]) flag = flag && true; else flag = flag && false;
                            if (standardIP[2] != "*")
                                if (standardIP[2] == currentIP[2]) flag = flag && true; else flag = flag && false;
                            if (standardIP[3] != "*")
                                if (standardIP[3] == currentIP[3]) flag = flag && true; else flag = flag && false;
                        }
                        flag = flag && (i.BeginDate <= DateTime.Now && i.EndDate >= DateTime.Now);
                        if (flag == true) break;
                    }
            }
            if (flag)
                return linq;
            else
                return null;
        }
        #endregion

        #region IWebDepartmentsRepository 成员

        public IQueryable<WebManageUsers> GetModel()
        {
            return GetEntities<WebManageUsers>();
        }

        public WebManageUsers Find(params object[] valueKeys)
        {
            return GetEntity<WebManageUsers>(valueKeys);
        }

        #endregion


        /// <summary>
        /// 得到客户端IP地址
        /// </summary>
        /// <returns></returns>
        string GetRealIp()
        {
            if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)
            {
                return HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
            }
            else
            {
                return HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
            }
        }




    }
}
